Props 觀念與使用


Posted by hoyi-23 on 2021-08-09

Vue每個元件的資料狀態是獨立的,若外面有資料需要傳入到元件內就需要使用 props 的屬性。

CodePen 實作練習

props

props 由外面向元件內傳遞資料,又分兩種方式: 靜態傳遞 / 動態傳遞

<div id="app">
  //動態傳遞(v-bind)
  <greet-component :name="person1"></greet-component>
  <greet-component :name="person2"></greet-component>
  <greet-component v-for="(each,key) in personArray" :name="each" :key="key"></greet-component>
  //靜態傳遞
  <greet-component name="Andy"></greet-component>
</div>
const app = Vue.createApp({
  data(){
    return{
      //使用data帶入
      person1: 'Jake',
      person2: 'Ted',
      personArray: ['one','two','three']
    }
  }
});
//props 是將外部的資料傳入到元件內
//Global Component
app.component('greet-component',{
  props: ['name'], //需要外部傳入資料
  template: `
    Hello {{name}}
  `
})

app.mount('#app')

命名注意

這邊要注意的是,我們在命名的時候:
props裡面命名使用小駝峰方式(imgUrl / isPublished / commentIds)
當在HTML上定義資料時不同單字要隔開(img-url / is-published / comment-ids)

單向數據流

我們在處理props時,要盡量維持單向數據流的觀念,不要反向的去修改
若要讓他返向修改資料,需要新定義一個變數來放新資料

<div id="app">
  <photo :img-url="url"></photo>
</div>
const app = Vue.createApp({
  data(){
    return{
      url: 'https://images.unsplash.com/photo-1522204538344-922f76ecc041?ixlib=rb-0.3.5&ixid=eyJhcHBfaWQiOjEyMDd9&s=50e38600a12d623a878983fc5524423f&auto=format&fit=crop&w=1351&q=80',
    }
  }
});
//Global Component
app.component('photo',{
  props: ['imgUrl'], 
  template: `
      <div>
          <img :src="imgUrl" class="img-fluid" alt="" />
          <input type="text" class="form-control" v-model="imgUrl">
      </div>
  `,
  data(){
    return{
      newUrl: this.imgUrl //這是props所傳進來的
    }
  }
})

app.mount('#app')

尚未宣告的變數

當我們要抓取遠端的資料時,可以使用v-if判斷資料內的某個東西有沒有存在,有的話在進行繪製HTML,不然在尚未抓完資料前就繪製出,會導致尚未宣告的錯誤。
如果你的資料匯入會有一些時間差,可子使用v-if將呈現往後移。

維持狀態與生命週期

當不希望元件整個重新生成的話可以加上 keep-alive










Related Posts

筆記、[NET101] 網路基礎概論 (1)

筆記、[NET101] 網路基礎概論 (1)

DAY45:Decode the Morse code, advanced

DAY45:Decode the Morse code, advanced

什麼是 Pure Function?在 React 當中的重要性是什麼?

什麼是 Pure Function?在 React 當中的重要性是什麼?


Comments